;
(function (window, angular) {
    'use strict';
    angular.module("Controller.Enterprise.StoreApply", [])
        .controller("StoreApplyCtrl", ["$scope", "$state", "ybWidget", "ybHttp", "MESG_TYPE", "$filter", "$timeout", "UserContextService", "EventBus", "Upload", "ybConfig", function ($scope, $state, ybWidget, ybHttp, MESG_TYPE, $filter, $timeout, UserContextService, EventBus, Upload, ybConfig) {
            $scope.activeFlag = [true, false, false, false, false];
            $scope.markInfo = {
                allChecked: false,
                curRow: -1
            };
            //门店管理分页信息
            $scope.pageInfo = {
                totalPages: 1,
                totalRows: 0,
                pageSize: 10,
                curPage: 1
            };
            // 是否提交
            $scope.submitted = false;
            // 搜索条件
            $scope.condition = {};
            $scope.toolbarConfig = {
                showColConfig: false,
            };
            // 门店列表
            $scope.dataList = [];
            // 需要上传的文件列表
            $scope.downloadFiles = [];
            // 详情信息
            $scope.detailInfo = {
                attachmentList: []
            };
            $scope.tbConf = {
                fixedWidth: 200,
                scrollWidth: 900,
                tableCol: [
                    {
                        type: "",
                        name: "门店名称",
                        dataField: "title",
                        width: 150,
                        isShow: true,
                        clickFn: "viewDetail",
                    },
                    {
                        type: "",
                        name: "接收方",
                        dataField: "receiveOrgName",
                        width: 110,
                        isShow: true,
                    },
                    {
                        type: "",
                        name: "状态",
                        dataField: "statusStr",
                        width: 100,
                        isShow: true,
                    },
                    {
                        type: "",
                        name: "初审意见",
                        dataField: "firstAdvice",
                        width: 120,
                        isShow: true,
                    },
                    {
                        type: "",
                        name: "终审意见",
                        dataField: "finalAdvice",
                        width: 120,
                        isShow: true,
                    },
                    {
                        type: "operate",
                        name: "操作",
                        dataField: "",
                        width: 200,
                        isShow: true,
                        isFixed: true,
                    }
                ]
            };

            $scope.tabFlag = {};
            var tabFlag = {
                0: "新增",
                1: "编辑"
            };

            var btnPermissionCode = {
                storeApplyAdd: window.ActionCode.storeApplyAdd,
                storeApplyEdit: window.ActionCode.storeApplyEdit,
                storeApplyRevoke: window.ActionCode.storeApplyRevoke,
                storeApplyFirstAuth: window.ActionCode.storeApplyFirstAuth,
                storeApplyFinalAuth: window.ActionCode.storeApplyFinalAuth,
                storeApplyFinish: window.ActionCode.storeApplyFinish,
                storeApplyDelete: window.ActionCode.storeApplyDelete,
            };

            $scope.btnPermission = {
                storeApplyAdd: true,
                storeApplyEdit: true,
                storeApplyRevoke: true,
                storeApplyFirstAuth: true,
                storeApplyFinalAuth: true,
                storeApplyFinish: true,
                storeApplyDelete: true
            };

            function setBtnPermission() {
                for (var key in btnPermissionCode) {
                    $scope.btnPermission[key] = UserContextService.CheckPermission([btnPermissionCode[key]]);
                }
            }

            $scope.setFixedWidth = function () {
                $scope.tbStyle = {
                    fixedWidth: {left: $scope.tbConf.fixedWidth + "px"}
                };
            };

            // 切换页签
            $scope.changeTab = function (index) {
                $scope.activeFlag = [false, false, false, false, false];
                $scope.activeFlag[index] = true;
                $scope.submitted = false;
                switch (index) {
                    case 0:
                        initData();
                        break;
                    default:
                        break;
                }
            };

            function initData () {
                $scope.detailInfo = {};
                $scope.downloadFiles = [];
                $scope.tabFlag = {};
            }

            // 选择表格行
            $scope.selectRow = function (index) {
                $scope.markInfo.curRow = index
            };

            // 表格列点击事件
            $scope.tdClick = function (item, fnType) {
                switch (fnType) {
                    case "viewDetail":
                        viewDetail(item);
                        break;
                    default:
                        break;
                }
            };

            $scope.switchToolbar = function (toolbar) {
                if (!!$scope.toolbarConfig["show" + toolbar]) {
                    $scope.toolbarConfig["show" + toolbar] = false;
                } else {
                    $timeout(function () {
                        $scope.toolbarConfig["show" + toolbar] = true;
                    });
                }
            };

            $scope.cancel = function () {
                $scope.changeTab(0);
            };

            // 搜索门店列表
            $scope.search = function (curPage) {
                if (!!curPage) {
                    $scope.pageInfo.curPage = curPage;
                }
                getDataList();
            };

            // 获取门店列表数据
            function getDataList() {
                var reqUrl = "/agentApply/listStore";
                var param = {
                    pageSize: $scope.pageInfo.pageSize,
                    pageNum: $scope.pageInfo.curPage,
                    filters: $scope.condition
                };
                ybHttp.Post('device', reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    angular.forEach(resp.value.list, function (item) {
                        item.isChecked = false;
                        item.statusStr = $filter('ProgressStatus')(item.status, 'exhibitionAuditStatus');
                    });
                    $scope.pageInfo.totalRows = resp.value.total;
                    $scope.pageInfo.totalPages = resp.value.pages;
                    $scope.dataList = resp.value.list;
                });
            }

            // 查看详情
            function viewDetail(item) {
                getDataDetail(item.id).then(function (value) {
                    if (value) {
                        $scope.detailInfo = value;
                        $scope.changeTab(2);
                    }
                });
            }

            // 获取门店详情
            var getDataDetail = function (id) {
                var service = "device";
                var reqUrl = "/agentApply/item";
                return ybHttp.Get(service, reqUrl, {id: id}).then(function (res) {
                    if (res.code !== 0) {
                        ybWidget.ShowMessage(res, MESG_TYPE.Error);
                        return false;
                    }
                    return res.value;
                });
            };

            // 选择主机厂
            function getOrgs () {
                var url = '/agentApply/listSapComs';
                ybHttp.Get('device', url).then(function (res) {
                    if (res.code !== 0) {
                        ybWidget.ShowMessage(res, MESG_TYPE.Error);
                        return;
                    }
                    $scope.companyList = res.value;
                })
            }

            //编辑按钮
            $scope.editData = function (item) {
                getOrgs();
                getDataDetail(item.id).then(function (res) {
                    $scope.detailInfo = res;
                    $scope.tabFlag.name = tabFlag[1];
                    $scope.tabFlag.type = 1;
                    $scope.changeTab(1);
                })
            };

            //新增按钮
            $scope.addData = function () {
                $scope.detailInfo = {
                    attachmentList: [],
                    files: []
                };
                getOrgs();
                $scope.tabFlag.name = tabFlag["0"];
                $scope.tabFlag.type = 0;
                $scope.changeTab(1);
            };

            $scope.saveData = function (valid, type) {
                if (!valid) {
                    $scope.submitted = true;
                    return;
                }
                // 编辑和提交的接口不一样 分别处理
                if ($scope.tabFlag.type === 0) {
                    savePost(type);
                } else {
                    editSavePost(type);
                }
            };

            // 保存到后台
            function savePost (type) {
                var url = ybConfig.getConfig().baseUrl.UploadSite + ybConfig.getConfig().serviceName.device + '/agentApply/saveStore';
                if (type === 1) {
                    url = ybConfig.getConfig().baseUrl.UploadSite + ybConfig.getConfig().serviceName.device + '/agentApply/commitStore';
                }
                var param = angular.copy($scope.detailInfo);
                param.file = $scope.downloadFiles;
                Upload.upload({
                    url: url,
                    method: 'POST',
                    data: param
                }).then(function (res) {
                    if (res.data.code !== 0) {
                        ybWidget.ShowMessage(res, MESG_TYPE.Error);
                        return false;
                    }
                    ybWidget.ShowToaster("success", "操作成功");
                    $scope.changeTab(0);
                    $scope.search(1);
                }, function (res) {
                    ybWidget.ShowMessage(res, MESG_TYPE.Error);
                    return false;
                });
            }

            // 提交到后台
            function editSavePost (type) {
                var url = '/agentApply/updateSave';
                if (type === 1) {
                    url = '/agentApply/updateCommit';
                }
                var param = angular.copy($scope.detailInfo);
                ybHttp.Post('device', url, param).then(function (res) {
                    if (res.code !== 0) {
                        ybWidget.ShowMessage(res, MESG_TYPE.Error);
                        return;
                    }
                    ybWidget.ShowToaster('success', '操作成功');
                    $scope.search(1);
                    $scope.changeTab(0);
                });
            }

            // 选择附件
            $scope.chooseFile = function (file) {
                if (!file) return;
                if (!/\.(xlsx|xls|doc|docx|pdf|zip|rar|XLSX|XLS|DOC|DOCX|PDF)$/.test(file.name)) {
                    ybWidget.ShowMessage("请选择 .xlsx .xls .doc .docx .pdf .zip .rar  格式的文件，最大不能超过50M", MESG_TYPE.Error);
                    return;
                }
                $scope.downloadFiles.push(file);
            };

            // 进入初审页面
            $scope.goFirstAuth = function (item) {
                getDataDetail(item.id).then(function (value) {
                    if (value) {
                        $scope.detailInfo = value;
                        $scope.changeTab(3);
                    }
                });
            };

            // 初审审核通过
            $scope.firstAuthPass = function () {
                var url = '/agentApply/firstAudit';
                var param = {
                    id: $scope.detailInfo.id,
                    firstAdvice: $scope.detailInfo.firstAdvice
                };
                ybHttp.Post('device', url, param).then(function (res) {
                    if (res.code !== 0) {
                        ybWidget.ShowMessage(res, MESG_TYPE.Error);
                        return;
                    }
                    ybWidget.ShowToaster('success', '操作成功');
                    $scope.search(1);
                    $scope.changeTab(0);
                })
            };

            // 进入终审页面
            $scope.goLastAuth = function (item) {
                getDataDetail(item.id).then(function (value) {
                    if (value) {
                        $scope.detailInfo = value;
                        $scope.changeTab(4);
                    }
                });
            };

            // 终审审核通过
            $scope.lastAuthPass = function () {
                var url = '/agentApply/finalAudit';
                var param = {
                    id: $scope.detailInfo.id,
                    finalAdvice: $scope.detailInfo.finalAdvice
                };
                ybHttp.Post('device', url, param).then(function (res) {
                    if (res.code !== 0) {
                        ybWidget.ShowMessage(res, MESG_TYPE.Error);
                        return;
                    }
                    ybWidget.ShowToaster('success', '操作成功');
                    $scope.search(1);
                    $scope.changeTab(0);
                })
            };

            // 审核拒绝
            $scope.auditReturn = function () {
                var url = '/agentApply/auditReturn';
                var param = {
                    id: $scope.detailInfo.id,
                    finalAdvice: $scope.detailInfo.finalAdvice,
                    firstAdvice: $scope.detailInfo.firstAdvice
                };
                ybHttp.Post('device', url, param).then(function (res) {
                    if (res.code !== 0) {
                        ybWidget.ShowMessage(res, MESG_TYPE.Error);
                        return;
                    }
                    ybWidget.ShowToaster('success', '操作成功');
                    $scope.search(1);
                    $scope.changeTab(0);
                })
            };

            // 完结
            $scope.finish = function (id) {
                var url = '/agentApply/finish';
                ybWidget.ShowMessage("确定要完结吗？", MESG_TYPE.Ask).then(function () {
                    ybHttp.Get('device', url, {applyId: id}).then(function (res) {
                        if (res.code !== 0) {
                            ybWidget.ShowMessage(res, MESG_TYPE.Error);
                            return;
                        }
                        ybWidget.ShowToaster('success', '操作成功');
                        $scope.search(1);
                    })
                });
            };

            // 撤回
            $scope.revoke = function (id) {
                var url = '/agentApply/revoke';
                ybWidget.ShowMessage("确定要撤回吗？", MESG_TYPE.Ask).then(function () {
                    ybHttp.Get('device', url, {applyId:id}).then(function (res) {
                        if (res.code !== 0) {
                            ybWidget.ShowMessage(res, MESG_TYPE.Error);
                            return;
                        }
                        ybWidget.ShowToaster('success', '操作成功');
                        $scope.search(1);
                    })
                });
            };

            $scope.deleteSingle = function (id) {
                deleteExhibition(id);
            };

            // 删除门店
            function deleteExhibition (id) {
                var url = '/agentApply/deleteApply';
                ybWidget.ShowMessage("确定要删除吗？", MESG_TYPE.Ask).then(function () {
                    ybHttp.Get('device', url, {applyId: id}).then(function (res) {
                        if (res.code !== 0) {
                            ybWidget.ShowMessage(res, MESG_TYPE.Error);
                            return;
                        }
                        ybWidget.ShowToaster('success', '操作成功');
                        $scope.search(1);
                    })
                });
            }

            // 新增时候的附件删除 不涉及后端
            $scope.deleteAddDoc = function (index) {
                $scope.downloadFiles.splice(index, 1);
            };

            // 编辑时候的附件删除 涉及后端
            $scope.deleteEditDoc = function (index, attachId) {
                var url = '/agentApply/deleteAttach';
                var param = {
                    attachId: attachId,
                    applyId: $scope.detailInfo.id
                };
                ybHttp.Get('device', url, param).then(function (res) {
                    if (res.code !== 0) {
                        ybWidget.ShowMessage(res, MESG_TYPE.Error);
                        return;
                    }
                    ybWidget.ShowToaster('success', '操作成功');
                    $scope.detailInfo.attachmentList.splice(index, 1);
                })
            };

            // 上传附件
            $scope.uploadDoc = function (file) {
                if (!file) {
                    return;
                }
                if (!/\.(xlsx|xls|doc|docx|pdf|zip|rar|XLSX|XLS|DOC|DOCX|PDF)$/.test(file.name)) {
                    ybWidget.ShowMessage("请选择 .xlsx .xls .doc .docx .pdf .zip .rar  格式的文件，最大不能超过50M", MESG_TYPE.Error);
                    return;
                }
                return Upload.upload({
                    url: ybConfig.getConfig().baseUrl.UploadSite + ybConfig.getConfig().serviceName.device + '/agentApply/uploadAttach',
                    data: {file: file, id: $scope.detailInfo.id}
                }).then(function (res) {
                    if (res.data && res.data.code !== 0) {
                        ybWidget.ShowMessage(res.data, MESG_TYPE.Error);
                        return false;
                    }
                    var fileObj = {};
                    fileObj.fileName = file.name;
                    $scope.detailInfo.attachmentList.push(fileObj);
                    return true;
                }, function (res) {
                    ybWidget.ShowMessage(res, MESG_TYPE.Error);
                    return false;
                });
            };

            // 下载附件
            $scope.downloadAttach = function (item) {
                window.location.href = ybHttp.RequestUrl("device", "/agentApply/downloadAttach") + '?applyId=' + item.applyId +"&attachId=" + item.id;
            };

            (function () {
                getDataList();
                $scope.setFixedWidth();
                UserContextService.SetBtnPermission(setBtnPermission);
            })();
        }])
    ;
})(window, window.angular);
